package com.woniu108.extra.controller;


import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.woniu108.carService.commos.dto.AccountDto;
import com.woniu108.carService.commos.dto.FriendListDto;
import com.woniu108.carService.commos.exception.WoniuException;
import com.woniu108.carService.commos.model.Result;
import com.woniu108.carService.commos.util.JWTUtil;
import com.woniu108.carService.commos.util.RedisUtil;
import com.woniu108.extra.client.PersonClient;
import com.woniu108.extra.model.FriendList;
import com.woniu108.extra.service.FriendListService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 好友列表 前端控制器
 * </p>
 *
 * @author yanxi
 * @since 2024-05-23
 */
@RestController
@RequestMapping("/friendList")
@Api(tags = "客服聊天列表服务接口")
public class FriendListController {

    @Resource
    private RedisUtil redisUtil;
    @Resource
    private FriendListService friendListService;
    @Resource
    private PersonClient personClient;

    public String getUserId(String token){
        String refreshToken=redisUtil.getString(token);
        String userId= JWTUtil.parseUserToken(refreshToken).get("userId").toString();
        return userId;
    }
    public String getAdminId(String token){
        String refreshToken=redisUtil.getString(token);
        String adminId= JWTUtil.parseAdminToken(refreshToken).get("adminId").toString();
        return adminId;
    }

    /**
     * 获取管理员的聊天列表
     * @param adminId 管理员编号
     * @return
     */
    @GetMapping("/getAdminChatList/{adminId}.api")
    @ApiOperation("获取管理员/客服的的聊天列表")
    public Result<List<FriendListDto>> getAdminChatList(@PathVariable("adminId") String adminId){
        QueryWrapper<FriendList> wrapper=new QueryWrapper<>();
        System.out.println(adminId);
        wrapper.eq("account_id",adminId);
        List<FriendList> list = friendListService.list(wrapper);
        System.out.println(list);
        List<FriendListDto> dtos = new ArrayList<>();
        for (FriendList friendList : list) {
            FriendListDto dto = BeanUtil.toBean(friendList, FriendListDto.class);
            Result<AccountDto> result = personClient.getByCommonId(dto.getAccountId());
            if(result.getCode()!=200) throw new WoniuException(result.getMsg(),result.getCode());
            Result<AccountDto> result1 = personClient.getByCommonId(dto.getFriendAccountId());
            if(result1.getCode()!=200) throw new WoniuException(result1.getMsg(),result1.getCode());
            dto.setAccountName(result.getData().getAccountName());
            dto.setFriendAccountName(result1.getData().getAccountName());
            dtos.add(dto);
        }
        System.out.println(dtos);
        return Result.newListInstance(FriendListDto.class).setData(dtos);
    }
}

